import numpy as np
from Parameter import *

restBuffer = np.zeros(0, dtype=np.int8)
FrameBeginIndex = []


def parse_buffer(srcbuf):
    global restBuffer
    Chirps = np.zeros([0, FrameBytesCount], dtype=np.uint8)
    # 按水平方向堆叠数组
    SrcBuf = np.hstack((restBuffer, srcbuf))
    nLen = SrcBuf.size

    # 清空上一缓存的数据
    FrameBeginIndex.clear()
    restBuffer = np.zeros(0, dtype=np.int8)

    nChirpHeadNum = 0  # 统计buffer中有多少个[0x55, 0xAA]

    i = 0
    while i < nLen - 1:
        if SrcBuf[i] == 0x88 and SrcBuf[i + 1] == 0xAF and SrcBuf[i + 2] == 0x1C:
            nChirpHeadNum += 1
            FrameBeginIndex.append(i)
            i += (FrameBytesCount - 3)

        i += 1
        nChirpNum = nChirpHeadNum - 1  # 最后一个ChirpHead以及后面的数据存入restBuffer

    for i in range(nChirpNum):
        if FrameBeginIndex[i + 1] - FrameBeginIndex[i] == FrameBytesCount:
            # 按垂直方向堆叠数组
            Chirps = np.vstack((Chirps, SrcBuf[FrameBeginIndex[i]:FrameBeginIndex[i + 1]]))
        else:
            print("loss")
            print(FrameBeginIndex[i], FrameBeginIndex[i + 1])

    # 最后一个ChirpHead以及后面的数据存入restBuffer
    restBuffer = SrcBuf[FrameBeginIndex[nChirpHeadNum - 1]:]
    return Chirps


def trs15(x):
    if x > (2 ** 15):
        x_real = x - (2 ** 16)
    else:
        x_real = x
    return x_real
